<template>
  <ContentWrap v-loading="formLoading">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="标签名称" prop="labelName">
        <el-input v-model="formData.labelName" placeholder="请输入标签名称" />
      </el-form-item>
      <el-form-item label="包含功能" prop="functionType">
        <el-radio-group v-model="formData.functionType">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.FUNCTION_VALUE)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item style="float: right">
        <el-button :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

</template>
<script setup lang="ts">
import { SupplyLabelApi, SupplyLabelVO } from '@/api/wine/supplylabel'
import { useTagsViewStore } from '@/store/modules/tagsView'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";

/** 供求标签管理 表单 */
defineOptions({ name: 'SupplyLabelForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  labelName: undefined,
  functionType: undefined
})
const formRules = reactive({
  labelName: [{ required: true, message: '标签名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const getDetail = async () => {
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SupplyLabelApi.getSupplyLabel(id)
    } finally {
      formLoading.value = false
    }
  }
}


onMounted(async () => {
  await getDetail()
})
const id = params.id as unknown as number


const close = () => {
  delView(unref(currentRoute))
  push({ name: 'SupplyLabel' })
}
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SupplyLabelVO
    if (!id) {
      await SupplyLabelApi.createSupplyLabel(data)
      message.success(t('common.createSuccess'))
    } else {
      await SupplyLabelApi.updateSupplyLabel(data)
      message.success(t('common.updateSuccess'))
    }
    close()
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}
</script>
